//
//  PersonInfoViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/4/15.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "ThreeLevelPickerView.h"
#import "UICustomActionSheet.h"
#import "STActionSheet.h"
#import "DZNPhotoEditorViewController.h"
#import "UIImagePickerController+Edit.h"


#import "ScroButton.h"

@interface PersonInfoViewController ()
<UIActionSheetDelegate>

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UIImageView *headerImaege;//头像
@property (strong, nonatomic) IBOutlet UITextField *nameTextField;//昵称
@property (strong, nonatomic) IBOutlet UITextField *phoneNumberTextField;//手机号
@property (strong, nonatomic) IBOutlet UITextField *birthdayTextField;//生日
@property (strong, nonatomic) IBOutlet UIButton *backButton;

@property(nonatomic,strong)ScroButton * sexButton;

@property(nonatomic,strong)NSString * headImageStr;
@end

@implementation PersonInfoViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hadLogin) name:@"hadLogin" object:nil];
    _headImageStr = @"";
    
    [self initViewLayout];
    [self getUserInfo];
}


- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];

    _scroview.contentSize = flexibleSize(CGSizeMake(320, 505), NO);
    
    ScroButton * button = [[ScroButton alloc]initWithFrame:flexibleFrame(CGRectMake(248, 166, 48, 23), NO)];
    button.defaultColor = [UIColor colorWithRed:0.988 green:0.439 blue:0.035 alpha:1.000];
    button.selectedColor = [UIColor colorWithRed:0.063 green:0.506 blue:0.835 alpha:1.000];
    button.defaultTitle = @"女";
    button.selectedTitle = @"男";
    button.circleColor = [UIColor whiteColor];
    button.textColor = [UIColor whiteColor];
    button.textFont = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
    button.ifSelected = YES;
    button.changeSelected = ^(BOOL ifSelected){
        
    };
    [self.scroview addSubview:button];
    _sexButton = button;

    _headerImaege.layer.masksToBounds = YES;
    _headerImaege.layer.cornerRadius = 24*VerticalRatio();
    _phoneNumberTextField.userInteractionEnabled = NO;
    
}

- (IBAction)back:(id)sender {
    [self backBtn];
}


- (void)hadLogin{
    [self backBtn];
}



#pragma mark=====获取用户信息
- (void)getUserInfo{
    
    _headImageStr = [NSString stringWithFormat:@"%@",self.attestDic[@"museImage"]];
    if (_headImageStr && _headImageStr.length>0 && ![self.attestDic[@"museImage"] isEqual:[NSNull null]]) {
        [self.headerImaege sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_headImageStr]]];
    }
    self.nameTextField.text = [NSString stringWithFormat:@"%@",self.attestDic[@"museNickName"]];
    self.phoneNumberTextField.text = [NSString stringWithFormat:@"%@",self.attestDic[@"museUserName"]];
    self.birthdayTextField.text = [NSString stringWithFormat:@"%@",self.attestDic[@"museBirthday"]];
    NSString *Str = [NSString stringWithFormat:@"%@",self.attestDic[@"museSex"]];
    if ([Str isEqualToString:@"0"]) {
        _sexButton.ifSelected = YES;
    } else if ([Str isEqualToString:@"1"]) {
        _sexButton.ifSelected = NO;
    }
}

#pragma mark=====修改个人资料
- (IBAction)save:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_headImageStr forKey:@"museImage"];
    [dic setObject:self.nameTextField.text forKey:@"museNickName"];
    if (_sexButton.ifSelected) {
        [dic setObject:@"0" forKey:@"museSex"];
    } else if (!_sexButton.ifSelected) { 
        [dic setObject:@"1" forKey:@"museSex"];
    }
    [dic setObject:self.birthdayTextField.text forKey:@"museBirthday"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_updateMember withHttpType:@"POST" withTag:JY_JY_updateMember];
}



#pragma mark == 修改生日
- (IBAction)changeBrithday:(id)sender {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    NSDate * date  = [[NSDate alloc]init];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//格式化
    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
    NSString * string =[formatter stringFromDate:date];
    NSInteger Year = [[string substringToIndex:4]integerValue];
    NSInteger Month = [[string substringWithRange:NSMakeRange(5, 2)]integerValue];
    NSInteger  Day = [[string substringFromIndex:8]integerValue];
    if (self.birthdayTextField.text.length>=10) {
        Year = [[self.birthdayTextField.text substringToIndex:4]integerValue];
        Month = [[self.birthdayTextField.text substringWithRange:NSMakeRange(5, 2)]integerValue];
        Day = [[self.birthdayTextField.text substringFromIndex:8]integerValue];
    }
    
    
    ThreeLevelPickerView * pickerView = [[ThreeLevelPickerView alloc]initWithSelectedAtRows:@[@(Year-1),@(Month-1),@(Day-1)] complect:^(NSString *str) {
        self.birthdayTextField.text = str;
    }];
    [pickerView show];

}




#pragma mark == 修改头像
- (IBAction)header:(id)sender {
    PhotoPopView * photoPopView = [[PhotoPopView alloc]initWithcomplect:^(NSInteger index) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UICustomActionSheet* actionSheet = [[UICustomActionSheet alloc] initWithTitle:@"" delegate:nil buttonTitles:@[@"",@""]];
            
            [actionSheet setButtonColors:@[[UIColor clearColor]]];
            [actionSheet setBackgroundColor:[UIColor clearColor]];
            
            [actionSheet setSubtitle:@""];
            [actionSheet setSubtitleColor:[UIColor clearColor]];
            
            [actionSheet showInView:self.view];
            
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            [actionSheet hideAlert];
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                 
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.headerImaege.image = image;
                    self.headerImaege.layer.masksToBounds = YES;
                    self.headerImaege.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.headerImaege.image = image;
                    self.headerImaege.layer.masksToBounds = YES;
                    self.headerImaege.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
            
        }else {
            UIActionSheet *ss=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"" destructiveButtonTitle:@"" otherButtonTitles:@"", nil];
            [ss showInView:self.view];
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            [ss dismissWithClickedButtonIndex:0 animated:YES];
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.headerImaege.image = image;
                    self.headerImaege.layer.masksToBounds = YES;
                    self.headerImaege.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.headerImaege.image = image;
                    self.headerImaege.layer.masksToBounds = YES;
                    self.headerImaege.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
        }

    }];
    [photoPopView show];
}


#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
    NSString *url = [NSString stringWithFormat:@"%@",IP_Address_IMAGE];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.7);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [ [Common getLoginInfo] objectForKey:Key_User_password];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
    //    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    //    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    NSString * image = dictionary[@"title"];
    if (image.length>0){
        _headImageStr = image;
    }else{
        _headImageStr = @"";
    }
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    if (tag==JY_JY_updateMember) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:@"保存成功"  withStatus:1 dismissAfter:1];
            [self backBtn];
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
        
    //
    
    [self dismissWaitDialog];
        
        
}







@end
